/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainForm.java
 *
 * Created on Jun 12, 2012, 4:27:38 PM
 */
package javamailclient;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import net.lingala.zip4j.exception.ZipException;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 
 * @author Abigail
 */
public class MainForm extends javax.swing.JFrame {

	// public Folder folder = null;
	public MailUtilities mailUtilities = null;
	public int countNewMessage = 0;
	public int countInboxMessage = 0;

	/** Creates new form MainForm */
	public MainForm() {
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		jList1 = new javax.swing.JList();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenu();
		jMenu2 = new javax.swing.JMenu();
		progressBar = new javax.swing.JProgressBar();
		slpBodyContent = new javax.swing.JSplitPane();
		jTabRight = new javax.swing.JTabbedPane();
		jpnInbox = new javax.swing.JPanel();
		jScrollPane2 = new javax.swing.JScrollPane();
		jtbInbox = new javax.swing.JTable();
		jtbInbox.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2 && !e.isConsumed()) {
					e.consume();
					Thread thread = new Thread(new Runnable() {

						@Override
						public void run() {
							int row = jtbInbox.getSelectedRow();
							if (row == -1) {
								return;
							}
							int i = Integer.parseInt(jtbInbox
									.getValueAt(row, 0).toString());
							viewMessage(i);
						}
					});
					thread.start();
				}
			}
		});
		jPanel2 = new javax.swing.JPanel();
		jComboBox1 = new javax.swing.JComboBox();
		jbtnViewMessage = new javax.swing.JButton();
		jLabel1 = new javax.swing.JLabel();
		jTabbedPane1 = new javax.swing.JTabbedPane();
		jPanel1 = new javax.swing.JPanel();
		jpnSubject1 = new javax.swing.JPanel();
		jlbSubject1 = new javax.swing.JLabel();
		jlbFrom1 = new javax.swing.JLabel();
		jlbTo1 = new javax.swing.JLabel();
		jlbsendDate = new javax.swing.JLabel();
		jPanel6 = new javax.swing.JPanel();
		jScrollPane4 = new javax.swing.JScrollPane();
		jtxtContentHTML = new javax.swing.JEditorPane();
		pnAttachment = new javax.swing.JPanel();
		jButton5 = new javax.swing.JButton();
		jpnNewMessage = new javax.swing.JPanel();
		jPanel3 = new javax.swing.JPanel();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		jtxtTo = new javax.swing.JTextField();
		jtxtSubject = new javax.swing.JTextField();
		jButton1 = new javax.swing.JButton();
		pnAttachtmentSendMail = new javax.swing.JPanel();
		jScrollPane3 = new javax.swing.JScrollPane();
		jtxtComposeMail = new javax.swing.JEditorPane();
		jPanel5 = new javax.swing.JPanel();
		jbtnSendMail = new javax.swing.JButton();
		jcbxCrypto = new javax.swing.JComboBox();
		jcbxProtocol = new javax.swing.JComboBox();
		jLabel2 = new javax.swing.JLabel();
		jtxtKey = new javax.swing.JPasswordField();
		jbtnNewMail = new javax.swing.JButton();
		jcbxIsSign = new javax.swing.JCheckBox();
		jpnViewMessage = new javax.swing.JPanel();
		jpnSubject = new javax.swing.JPanel();
		jlbSubject = new javax.swing.JLabel();
		jlbFrom = new javax.swing.JLabel();
		jlbTo = new javax.swing.JLabel();
		jbtnAttachment = new javax.swing.JButton();
		jtxt = new javax.swing.JScrollPane();
		jtxtMailContent = new javax.swing.JEditorPane();
		jlTabLeft = new javax.swing.JPanel();
		jlbNewMessage = new javax.swing.JLabel();
		jlbInbox = new javax.swing.JLabel();
		jlbSent = new javax.swing.JLabel();
		jlbTrash = new javax.swing.JLabel();
		jlbTrash.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {

				Thread thread = new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							// TODO add your handling code here:
							// folder = mailUtilities.openFolder("inbox");
							retriveMessages(Flags.Flag.DELETED, true);
						} catch (UnsupportedEncodingException ex) {
							showError(ex.getMessage(), false);
							// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
							// null, ex);
						} catch (MessagingException ex) {
							// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
							// null, ex);
							showError(ex.getMessage(), false);
						}
					}
				});
				thread.start();

				thread.isInterrupted();
			}
		});
		jlbDrafts = new javax.swing.JLabel();
		jlbUnread = new javax.swing.JLabel();
		pnHeader = new javax.swing.JPanel();
		lbWelcome = new javax.swing.JLabel();
		jlbUnreadMessage = new javax.swing.JLabel();
		menuBar = new javax.swing.JMenuBar();
		connectMenu = new javax.swing.JMenu();
		helpMenu = new javax.swing.JMenu();
		aboutMenuItem = new javax.swing.JMenuItem();

		jList1.setModel(new javax.swing.AbstractListModel() {
			String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4",
					"Item 5" };

			public int getSize() {
				return strings.length;
			}

			public Object getElementAt(int i) {
				return strings[i];
			}
		});
		jScrollPane1.setViewportView(jList1);

		jMenu1.setText("File");
		jMenuBar1.add(jMenu1);

		jMenu2.setText("Edit");
		jMenuBar1.add(jMenu2);

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Java Client Mail");
		setName("mainframe"); // NOI18N
		setResizable(false);
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowOpened(java.awt.event.WindowEvent evt) {
				formWindowOpened(evt);
			}
		});

		slpBodyContent.setCursor(new java.awt.Cursor(
				java.awt.Cursor.DEFAULT_CURSOR));

		jTabRight.setMaximumSize(null);

		jtbInbox.setModel(new javax.swing.table.DefaultTableModel(
				new Object[][] {

				}, new String[] { " ", "From", "Subject", "Date" }) {
			Class[] types = new Class[] { java.lang.String.class,
					java.lang.String.class, java.lang.String.class,
					java.lang.String.class };
			boolean[] canEdit = new boolean[] { false, false, false, false };

			public Class getColumnClass(int columnIndex) {
				return types[columnIndex];
			}

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		jtbInbox.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
		jtbInbox.setGridColor(new java.awt.Color(153, 153, 153));
		jtbInbox.setIntercellSpacing(new java.awt.Dimension(2, 2));
		jtbInbox.setName("jtbInbox"); // NOI18N
		jtbInbox.setRowHeight(22);
		jtbInbox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
		jtbInbox.getTableHeader().setReorderingAllowed(false);
		jScrollPane2.setViewportView(jtbInbox);
		jtbInbox.getColumnModel()
				.getSelectionModel()
				.setSelectionMode(
						javax.swing.ListSelectionModel.SINGLE_SELECTION);
		jtbInbox.getColumnModel().getColumn(0).setMinWidth(0);
		jtbInbox.getColumnModel().getColumn(0).setPreferredWidth(0);
		jtbInbox.getColumnModel().getColumn(0).setMaxWidth(0);

		jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
				"Delete On Client", "Delete On Server", "Both" }));

		jbtnViewMessage.setText("View Message");

		jLabel1.setText("fectching ");

		btnDelete = new JButton("Delete");
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int row = jtbInbox.getSelectedRow();
				if (row == -1) {
					return;
				}
				int i = Integer
						.parseInt(jtbInbox.getValueAt(row, 0).toString());
				try {
					if (jComboBox1.getSelectedItem().toString()
							.equals("Delete On Client")) {
						mailUtilities.deleteOnClient(mailUtilities.folder
								.getMessage(i));
					} else if (jComboBox1.getSelectedItem().toString()
							.equals("Delete On Server")) {
						mailUtilities.deleteOnServer(mailUtilities.folder
								.getMessage(i));
					} else if (jComboBox1.getSelectedItem().toString()
							.equals("Both")) {
						mailUtilities.delete(mailUtilities.folder.getMessage(i));
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(
				jPanel2);
		jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(
				Alignment.LEADING).addGroup(
				jPanel2Layout
						.createSequentialGroup()
						.addGap(28)
						.addComponent(jbtnViewMessage)
						.addGap(18)
						.addComponent(jComboBox1, GroupLayout.PREFERRED_SIZE,
								GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(ComponentPlacement.UNRELATED)
						.addComponent(btnDelete)
						.addGap(66)
						.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 214,
								GroupLayout.PREFERRED_SIZE)
						.addContainerGap(205, Short.MAX_VALUE)));
		jPanel2Layout
				.setVerticalGroup(jPanel2Layout
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								jPanel2Layout
										.createSequentialGroup()
										.addContainerGap(
												GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addGroup(
												jPanel2Layout
														.createParallelGroup(
																Alignment.BASELINE)
														.addComponent(
																jComboBox1,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(
																jbtnViewMessage)
														.addComponent(
																jLabel1,
																GroupLayout.PREFERRED_SIZE,
																18,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(btnDelete))
										.addContainerGap()));
		jPanel2.setLayout(jPanel2Layout);

		jpnSubject1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

		jlbSubject1.setFont(new java.awt.Font("Tahoma", 1, 14));
		jlbSubject1.setText("subject");
		jlbSubject1.setMaximumSize(new java.awt.Dimension(857, 17));

		jlbFrom1.setText("from");

		jlbTo1.setText("to");

		jlbsendDate.setText("send date");

		javax.swing.GroupLayout jpnSubject1Layout = new javax.swing.GroupLayout(
				jpnSubject1);
		jpnSubject1.setLayout(jpnSubject1Layout);
		jpnSubject1Layout
				.setHorizontalGroup(jpnSubject1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jpnSubject1Layout
										.createSequentialGroup()
										.addGap(33, 33, 33)
										.addGroup(
												jpnSubject1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																jpnSubject1Layout
																		.createSequentialGroup()
																		.addGroup(
																				jpnSubject1Layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addComponent(
																								jlbTo1)
																						.addComponent(
																								jlbFrom1))
																		.addGap(80,
																				80,
																				80)
																		.addComponent(
																				jlbsendDate)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																				15,
																				Short.MAX_VALUE))
														.addComponent(
																jlbSubject1,
																javax.swing.GroupLayout.Alignment.TRAILING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																165,
																Short.MAX_VALUE))
										.addGap(630, 630, 630)));
		jpnSubject1Layout
				.setVerticalGroup(jpnSubject1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								jpnSubject1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(
												jlbSubject1,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addGroup(
												jpnSubject1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																jlbsendDate)
														.addComponent(jlbFrom1))
										.addGap(18, 18, 18)
										.addComponent(jlbTo1).addContainerGap()));

		jPanel6.setLayout(new javax.swing.BoxLayout(jPanel6,
				javax.swing.BoxLayout.X_AXIS));

		jtxtContentHTML.setEditable(false);
		jtxtContentHTML.setMaximumSize(null);
		jScrollPane4.setViewportView(jtxtContentHTML);

		jPanel6.add(jScrollPane4);

		pnAttachment.setLayout(new java.awt.GridLayout(10, 1, 0, 1));

		jButton5.setText("jButton5");
		pnAttachment.add(jButton5);

		jPanel6.add(pnAttachment);

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(jpnSubject1,
						javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE,
						832, Short.MAX_VALUE));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addComponent(
												jpnSubject1,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jPanel6,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												276, Short.MAX_VALUE)));

		jTabbedPane1.addTab("Message #1", jPanel1);

		javax.swing.GroupLayout jpnInboxLayout = new javax.swing.GroupLayout(
				jpnInbox);
		jpnInbox.setLayout(jpnInboxLayout);
		jpnInboxLayout.setHorizontalGroup(jpnInboxLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(jTabbedPane1,
						javax.swing.GroupLayout.DEFAULT_SIZE, 837,
						Short.MAX_VALUE)
				.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addComponent(jScrollPane2,
						javax.swing.GroupLayout.DEFAULT_SIZE, 837,
						Short.MAX_VALUE));
		jpnInboxLayout
				.setVerticalGroup(jpnInboxLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jpnInboxLayout
										.createSequentialGroup()
										.addComponent(
												jPanel2,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jScrollPane2,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												148,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jTabbedPane1,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												410, Short.MAX_VALUE)));

		jTabRight.addTab("Inbox", jpnInbox);

		jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

		jLabel4.setText("To:");

		jLabel5.setText("Subject:");

		jtxtTo.setText("anm.hcb.receiver201@gmail.com");
		jtxtTo.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jtxtToActionPerformed(evt);
			}
		});

		jButton1.setText("Attach File");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		pnAttachtmentSendMail.setBorder(javax.swing.BorderFactory
				.createEtchedBorder());
		pnAttachtmentSendMail.setLayout(new java.awt.GridLayout(1, 0));

		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(
				jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout
				.setHorizontalGroup(jPanel3Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel3Layout
										.createSequentialGroup()
										.addGap(166, 166, 166)
										.addGroup(
												jPanel3Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(jLabel4)
														.addComponent(jButton1)
														.addComponent(jLabel5))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												jPanel3Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																pnAttachtmentSendMail,
																javax.swing.GroupLayout.Alignment.TRAILING,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																jtxtTo,
																javax.swing.GroupLayout.Alignment.TRAILING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																568,
																Short.MAX_VALUE)
														.addComponent(
																jtxtSubject,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																568,
																Short.MAX_VALUE))
										.addContainerGap()));
		jPanel3Layout
				.setVerticalGroup(jPanel3Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel3Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel3Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel4)
														.addComponent(
																jtxtTo,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(18, 18, 18)
										.addGroup(
												jPanel3Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jLabel5)
														.addComponent(
																jtxtSubject,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addGroup(
												jPanel3Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																pnAttachtmentSendMail,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																jButton1,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																23,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addContainerGap(31, Short.MAX_VALUE)));

		jScrollPane3.setViewportView(jtxtComposeMail);

		jbtnSendMail.setText("Send");
		jbtnSendMail.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jbtnSendMailActionPerformed(evt);
			}
		});

		jcbxCrypto.setModel(new javax.swing.DefaultComboBoxModel(
				new String[] { "--choose cryptography--", "Symmetric",
						"Symmetric & Asymetric" }));
		jcbxCrypto.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jcbxCryptoActionPerformed(evt);
			}
		});

		jLabel2.setText("Key");

		jtxtKey.setText("12345678");

		jbtnNewMail.setText("New Mail");
		jbtnNewMail.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jbtnNewMailActionPerformed(evt);
			}
		});

		jcbxIsSign.setText("Sign On Mail ???");

		javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(
				jPanel5);
		jPanel5.setLayout(jPanel5Layout);
		jPanel5Layout
				.setHorizontalGroup(jPanel5Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel5Layout
										.createSequentialGroup()
										.addGap(27, 27, 27)
										.addComponent(jbtnSendMail)
										.addGap(18, 18, 18)
										.addComponent(jbtnNewMail)
										.addGap(66, 66, 66)
										.addComponent(
												jcbxCrypto,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addComponent(
												jcbxProtocol,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												119,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addComponent(jLabel2)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addComponent(
												jtxtKey,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												143,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addGap(18, 18, 18)
										.addComponent(jcbxIsSign)
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));
		jPanel5Layout
				.setVerticalGroup(jPanel5Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel5Layout
										.createSequentialGroup()
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addGroup(
												jPanel5Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																jbtnSendMail)
														.addComponent(
																jbtnNewMail)
														.addComponent(
																jcbxCrypto,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																jcbxProtocol,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																jtxtKey,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(jLabel2)
														.addComponent(
																jcbxIsSign))
										.addContainerGap()));

		javax.swing.GroupLayout jpnNewMessageLayout = new javax.swing.GroupLayout(
				jpnNewMessage);
		jpnNewMessage.setLayout(jpnNewMessageLayout);
		jpnNewMessageLayout.setHorizontalGroup(jpnNewMessageLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
				.addComponent(jScrollPane3));
		jpnNewMessageLayout
				.setVerticalGroup(jpnNewMessageLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jpnNewMessageLayout
										.createSequentialGroup()
										.addComponent(
												jPanel5,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												39,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jPanel3,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												138,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jScrollPane3,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												426, Short.MAX_VALUE)));

		jTabRight.addTab("New Message", jpnNewMessage);

		jpnSubject.setBorder(javax.swing.BorderFactory.createEtchedBorder());

		jlbSubject.setFont(new java.awt.Font("Tahoma", 1, 12));
		jlbSubject.setText("Subject");

		jlbFrom.setText("From:");

		jlbTo.setText("To:");

		jbtnAttachment.setText("Attachment");

		javax.swing.GroupLayout jpnSubjectLayout = new javax.swing.GroupLayout(
				jpnSubject);
		jpnSubject.setLayout(jpnSubjectLayout);
		jpnSubjectLayout
				.setHorizontalGroup(jpnSubjectLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jpnSubjectLayout
										.createSequentialGroup()
										.addGap(32, 32, 32)
										.addGroup(
												jpnSubjectLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jlbFrom)
														.addGroup(
																jpnSubjectLayout
																		.createSequentialGroup()
																		.addComponent(
																				jlbTo)
																		.addGap(311,
																				311,
																				311)
																		.addComponent(
																				jbtnAttachment,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				111,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addComponent(
																jlbSubject))
										.addContainerGap(363, Short.MAX_VALUE)));
		jpnSubjectLayout
				.setVerticalGroup(jpnSubjectLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jpnSubjectLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(jlbSubject)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												20, Short.MAX_VALUE)
										.addComponent(jlbFrom)
										.addGap(18, 18, 18)
										.addGroup(
												jpnSubjectLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(jlbTo)
														.addComponent(
																jbtnAttachment,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																18,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addContainerGap()));

		jtxtMailContent.setEnabled(false);
		jtxt.setViewportView(jtxtMailContent);

		javax.swing.GroupLayout jpnViewMessageLayout = new javax.swing.GroupLayout(
				jpnViewMessage);
		jpnViewMessage.setLayout(jpnViewMessageLayout);
		jpnViewMessageLayout
				.setHorizontalGroup(jpnViewMessageLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addComponent(jpnSubject,
								javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)
						.addComponent(jtxt,
								javax.swing.GroupLayout.Alignment.TRAILING));
		jpnViewMessageLayout
				.setVerticalGroup(jpnViewMessageLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jpnViewMessageLayout
										.createSequentialGroup()
										.addComponent(
												jpnSubject,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												jtxt,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												498, Short.MAX_VALUE)));

		jTabRight.addTab("View Message", jpnViewMessage);

		slpBodyContent.setRightComponent(jTabRight);

		jlTabLeft.setMaximumSize(null);

		jlbNewMessage.setText("New Message");
		jlbNewMessage
				.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
		jlbNewMessage.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jlbNewMessageMouseClicked(evt);
			}
		});

		jlbInbox.setText("Inbox");
		jlbInbox.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
		jlbInbox.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jlbInboxMouseClicked(evt);
			}
		});

		jlbSent.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

		jlbTrash.setText("Trash");
		jlbTrash.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

		jlbDrafts.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

		jlbUnread.setText("Undread ");
		jlbUnread.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
		jlbUnread.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				jlbUnreadMouseClicked(evt);
			}
		});

		javax.swing.GroupLayout jlTabLeftLayout = new javax.swing.GroupLayout(
				jlTabLeft);
		jlTabLeft.setLayout(jlTabLeftLayout);
		jlTabLeftLayout
				.setHorizontalGroup(jlTabLeftLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jlTabLeftLayout
										.createSequentialGroup()
										.addGap(34, 34, 34)
										.addGroup(
												jlTabLeftLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jlbTrash)
														.addComponent(jlbUnread)
														.addComponent(jlbInbox)
														.addComponent(jlbSent)
														.addComponent(jlbDrafts)
														.addComponent(
																jlbNewMessage))
										.addContainerGap(
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)));
		jlTabLeftLayout
				.setVerticalGroup(jlTabLeftLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jlTabLeftLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(jlbNewMessage)
										.addGap(18, 18, 18)
										.addComponent(jlbUnread)
										.addGap(20, 20, 20)
										.addComponent(jlbInbox)
										.addGap(18, 18, 18)
										.addGroup(
												jlTabLeftLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																jlTabLeftLayout
																		.createSequentialGroup()
																		.addComponent(
																				jlbSent)
																		.addGap(50,
																				50,
																				50)
																		.addComponent(
																				jlbDrafts))
														.addComponent(jlbTrash))
										.addContainerGap(484, Short.MAX_VALUE)));

		slpBodyContent.setLeftComponent(jlTabLeft);

		lbWelcome.setText("You're not log in");

		jlbUnreadMessage.setText("You got ");
		jlbUnreadMessage.setCursor(new java.awt.Cursor(
				java.awt.Cursor.HAND_CURSOR));

		javax.swing.GroupLayout pnHeaderLayout = new javax.swing.GroupLayout(
				pnHeader);
		pnHeader.setLayout(pnHeaderLayout);
		pnHeaderLayout.setHorizontalGroup(pnHeaderLayout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				pnHeaderLayout
						.createSequentialGroup()
						.addGap(23, 23, 23)
						.addComponent(lbWelcome)
						.addGap(18, 18, 18)
						.addComponent(jlbUnreadMessage,
								javax.swing.GroupLayout.PREFERRED_SIZE, 245,
								javax.swing.GroupLayout.PREFERRED_SIZE)
						.addContainerGap(596, Short.MAX_VALUE)));
		pnHeaderLayout
				.setVerticalGroup(pnHeaderLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								pnHeaderLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												pnHeaderLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(lbWelcome)
														.addComponent(
																jlbUnreadMessage))
										.addContainerGap(11, Short.MAX_VALUE)));

		connectMenu.setMnemonic('f');
		connectMenu.setText("Connect");
		connectMenu.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				connectMenuMouseClicked(evt);
			}
		});
		menuBar.add(connectMenu);

		helpMenu.setMnemonic('h');
		helpMenu.setText("Help");

		aboutMenuItem.setMnemonic('a');
		aboutMenuItem.setText("About");
		helpMenu.add(aboutMenuItem);

		menuBar.add(helpMenu);

		setJMenuBar(menuBar);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addComponent(slpBodyContent,
						javax.swing.GroupLayout.DEFAULT_SIZE, 959,
						Short.MAX_VALUE)
				.addComponent(pnHeader, javax.swing.GroupLayout.DEFAULT_SIZE,
						javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addComponent(pnHeader,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(slpBodyContent,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										645, Short.MAX_VALUE).addContainerGap()));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void connectMenuMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_connectMenuMouseClicked
		// viewConnectionDlg();
	}// GEN-LAST:event_connectMenuMouseClicked

	/**
	 * Láº¥y lÃªn nhá»¯ng message má»›i ká»ƒ tá»« láº§n cuá»‘i cÃ¹ng ng` dÃ¹ng
	 * má»Ÿ há»™p thÆ°
	 * 
	 * @param evt
	 */
	private void formWindowOpened(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowOpened
		// init progressbar
		// thÃªm sá»± kiá»‡n selection row vÃ o jtable
		addListSelectionListenerToJTable();
		jLabel1.setText("");
		try {

			// TODO add your handling code here:
			mailUtilities = connectionDlg.mailUtilities;

			// mailUtilities.getFolders();
			// open folder inbox
			mailUtilities.openFolder("INBOX");

			// count new message
			countNewMessage = mailUtilities.folder.getNewMessageCount();

			// count inbox message
			countInboxMessage = mailUtilities.folder.getMessageCount()
					- countNewMessage;

			jlbNewMessage.setText("New Message (" + countNewMessage + ")");

			jlbInbox.setText("Inbox (" + countInboxMessage + ")");

			lbWelcome.setText("Welcome, " + mailUtilities.getUserName() + " !");

			jlbUnreadMessage.setText("<html>You got <i>" + countNewMessage
					+ "</i> new message(s).");

			jlbUnread.setText("<html>Unread <i>("
					+ mailUtilities.folder.getUnreadMessageCount() + ")</i>");

			connectMenu.setEnabled(false);

			// retrive messages have flag RECENT: newest messages
			Thread thread = new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						retriveMessages(Flag.RECENT, true);
					} catch (MessagingException ex) {
						// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
						// null, ex);
						showError(ex.getMessage(), false);
					} catch (UnsupportedEncodingException ex) {
						// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
						// null, ex);
						showError(ex.getMessage(), false);
					}
				}
			});
			thread.start();
		} catch (MessagingException ex) {
			// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
			// null, ex);
			showError(ex.getMessage(), true);
		}
	}// GEN-LAST:event_formWindowOpened

	private void jtxtToActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jtxtToActionPerformed
		// TODO add your handling code
		// here:}//GEN-LAST:event_jtxtToActionPerformed
	}

	private void jlbInboxMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jlbInboxMouseClicked

		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// TODO add your handling code here:
					// folder = mailUtilities.openFolder("inbox");
					retriveInboxMessages();
				} catch (UnsupportedEncodingException ex) {
					showError(ex.getMessage(), false);
					// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
					// null, ex);
				} catch (MessagingException ex) {
					// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
					// null, ex);
					showError(ex.getMessage(), false);
				}
			}
		});
		thread.start();

		thread.isInterrupted();
	}// GEN-LAST:event_jlbInboxMouseClicked

	private void jlbNewMessageMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jlbNewMessageMouseClicked
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// TODO add your handling code here:
					// folder = mailUtilities.openFolder("inbox");
					retriveMessages(Flag.RECENT, true);
				} catch (UnsupportedEncodingException ex) {
					showError(ex.getMessage(), false);
					// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
					// null, ex);
				} catch (MessagingException ex) {
					// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
					// null, ex);
					showError(ex.getMessage(), false);
				}
			}
		});
		thread.start();

		thread.isInterrupted();
	}// GEN-LAST:event_jlbNewMessageMouseClicked

	private void jlbUnreadMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jlbUnreadMouseClicked
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// TODO add your handling code here:
					// folder = mailUtilities.openFolder("inbox");
					retriveMessages(Flag.SEEN, false);
				} catch (UnsupportedEncodingException ex) {
					showError(ex.getMessage(), false);
					// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
					// null, ex);
				} catch (MessagingException ex) {
					// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE,
					// null, ex);
					showError(ex.getMessage(), false);
				}
			}
		});
		thread.start();

		thread.isInterrupted();
	}// GEN-LAST:event_jlbUnreadMouseClicked

	private void jcbxCryptoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jcbxCryptoActionPerformed
		// TODO add your handling code here:
		// add selectionchanged event for cbxServerName
		int selectedIndex = jcbxCrypto.getSelectedIndex();
		jcbxProtocol.removeAllItems();
		if (selectedIndex == 1) {
			jcbxProtocol.addItem("AES");
			jcbxProtocol.addItem("DES");
			jcbxProtocol.addItem("Triple DES");
			// jtxtKey.setEnabled(true);
		} else if (selectedIndex == 2) {
			jcbxProtocol.addItem("AES & RSA");
			jcbxProtocol.addItem("DES & RSA");
			jcbxProtocol.addItem("TripleDES & RSA");
			// jtxtKey.setEnabled(false);
		}

	}// GEN-LAST:event_jcbxCryptoActionPerformed

	List<String> attachments = new ArrayList<String>();

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		JFileChooser fileChooser = new JFileChooser();
		int returnVal = fileChooser.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {

			String fileName = fileChooser.getSelectedFile().getName();
			JButton btn = new JButton(fileName + " [x]");
			btn.setToolTipText("Click here to remove this attachment");
			final Component temp = pnAttachtmentSendMail.add(btn);
			btn.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					pnAttachtmentSendMail.remove(temp);
				}
			});
			attachments.add(fileChooser.getSelectedFile().getAbsolutePath()
					.replace("\\", "/"));
		}
		// fileChooser.OPEN_DIALOG();
	}// GEN-LAST:event_jButton1ActionPerformed

	private void jbtnSendMailActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jbtnSendMailActionPerformed
		// TODO add your handling code here:
		String reveiverMail = jtxtTo.getText();
		String subject = jtxtSubject.getText();
		String content = jtxtComposeMail.getText();
		String key = jtxtKey.getText();
		boolean isSign = jcbxIsSign.isSelected();
		if (reveiverMail.equals("")) {
			showError("Báº¡n chÆ°a nháº­p email ngÆ°á»�i nháº­n", false);
			return;
		}

		int iSelectedAlgorithm = jcbxProtocol.getSelectedIndex();
		int iSelectedCrypto = jcbxCrypto.getSelectedIndex();
		// if (iSelectedCrypto == 0) {
		// showError("Báº¡n chÆ°a chá»�n phÆ°Æ¡ng phÃ¡p mÃ£ hÃ³a !!!", false);
		// return;
		// }
		String algorithm = getSelectedValue(iSelectedAlgorithm);

		try {
			switch (iSelectedCrypto) {
			case 1: {
				mailUtilities.sendSym(algorithm, reveiverMail, subject,
						content, attachments, key, isSign);
				break;
			}
			case 2: {
				mailUtilities.sendSymAndASym(algorithm, key, reveiverMail,
						subject, content, attachments, isSign);
				break;
			}
			default: {
				mailUtilities.send(reveiverMail, subject, content, attachments,
						isSign);
				break;
			}
			}
			showSuccess("Send mail success", false);

			clearAll();
		} catch (MessagingException ex) {
			showError(ex.getMessage(), false);
		} catch (Exception ex) {
			showError(ex.getMessage(), false);
		}
	}// GEN-LAST:event_jbtnSendMailActionPerformed

	private void clearAll() {
		pnAttachtmentSendMail.removeAll();
		jtxtComposeMail.setText("");
		jtxtMailContent.setText("");
		jtxtSubject.setText("");
		// jtxtTo.setText("");
		attachments = new ArrayList<String>();
	}

	private void jbtnNewMailActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jbtnNewMailActionPerformed
		// TODO add your handling code here:
		clearAll();
	}// GEN-LAST:event_jbtnNewMailActionPerformed

	private String getSelectedValue(int i) {
		String algorithm = "AES";
		switch (i) {
		case 0: {
			algorithm = "AES";
			break;
		}
		case 1: {
			algorithm = "DES";
			break;
		}
		case 2: {
			algorithm = "DESede";
			break;
		}
		default:
			break;
		}
		return algorithm;
	}

	/**
	 * add listSelectionListener to jTable jtbInbox
	 */
	private void addListSelectionListenerToJTable() {

		ListSelectionModel selectionModel = jtbInbox.getSelectionModel();
		selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		selectionModel.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				// thread.interrupt();
			}
		});

	}

	private void downloadAttachment(MyAttachment attachment)
			throws IOException, MessagingException {
		String outputFilename = "";
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int ok = fileChooser.showSaveDialog(null);
		if (ok == JFileChooser.APPROVE_OPTION) {
			outputFilename = fileChooser.getSelectedFile().getAbsolutePath()
					+ "\\" + attachment.getFileName();// .getParent() +
														// "/test.private";
			javax.mail.BodyPart p = attachment.getContent();
			InputStream stream = p.getInputStream();
			File f = new File(outputFilename);
			f.createNewFile();

			OutputStream out = new FileOutputStream(outputFilename);
			byte buf[] = new byte[p.getSize()];
			int len;
			while ((len = stream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.close();
		}

	}

	private void viewMessage(int i) {
		final loadingDlg loadingDialog = new loadingDlg(this);
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				loadingDialog.show();
			}
		});
		int cryptoName = mailUtilities.getCryptographyName();

		try {

			Message msg = mailUtilities.folder.getMessage(i);

			MyClientMail myMail = new MyClientMail();
			myMail = mailUtilities.receiveSymAnAsym(msg);
			// folder.getMessage(i).setFlag(Flag.SEEN, true);
			// ATTACHMENT(S):

			switch (cryptoName) {
			case 1: {
				String algorithm = mailUtilities.getSymAlgorithmName();
				myMail = mailUtilities.receiveSym(msg, algorithm);
				break;
			}
			case 2: {
				// String algorithm = mailUtilities.getSymAlgorithmName();
				myMail = mailUtilities.receiveSymAnAsym(msg);
				break;
			}
			default: {
				// khÃ´ng mÃ£ hÃ³a
				myMail = mailUtilities.receive(msg);
				break;
			}
			}

			jlbSubject1.setText(myMail.getSubject());// (obs[1].toString());

			jlbFrom1.setText("FROM: " + myMail.getFrom());// obs[0].toString());

			jlbTo1.setText("TO: " + myMail.getTo());// obs[3].toString());

			jlbsendDate.setText("DATE: " + myMail.getSendDate());// obs[2].toString());

			if (myMail.getContentType() == null) {
				myMail.setContentType("text/plain");
			}
			jtxtContentHTML.setContentType(myMail.getContentType());

			jtxtContentHTML.setText(myMail.getTextPlainContent());

			pnAttachment.removeAll();

			for (final MyAttachment att : myMail.attachments) {
				JButton btn = new JButton(att.getFileName());
				pnAttachment.add(btn);
				btn.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						try {
							downloadAttachment(att);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (MessagingException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				});
			}
			loadingDialog.dispose();
		} catch (ZipException ex) {
			Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null,
					ex);
			loadingDialog.dispose();
			showError(ex.getMessage(), false);
		} catch (NoSuchAlgorithmException ex) {
			Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null,
					ex);
			loadingDialog.dispose();
			showError(ex.getMessage(), false);
		} catch (InvalidKeySpecException ex) {
			Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null,
					ex);
			loadingDialog.dispose();
			showError(ex.getMessage(), false);
		} catch (Exception ex) {
			Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null,
					ex);
			loadingDialog.dispose();
			showError(ex.getMessage(), false);
		}
	}

	private void receiveMail(Message msg) throws MessagingException,
			IOException {
		jtxtContentHTML.setText("");
		String contentType = msg.getContentType();

		if (contentType.toLowerCase().contains("text/html")) {

			jtxtContentHTML.setContentType(contentType);

			jtxtContentHTML.setText(msg.getContent().toString());

		} else if (contentType.contains("multipart/")) {
			MimeMultipart multipart = (MimeMultipart) msg.getContent();

			int count = multipart.getCount();

			String bodyPartContentType = "";

			Object bodyPartContent = "";

			String txt = "";

			for (int p = 0; p < count; p++) {
				BodyPart bodyPart = multipart.getBodyPart(p);

				DataHandler dataHandler = bodyPart.getDataHandler();

				bodyPartContentType = bodyPart.getContentType();

				String dis = bodyPart.getDisposition();

				bodyPartContent = dataHandler.getContent();

				if ("attachment".equals(dis)) {
					addButtonToAttachmentPanel(bodyPart);
				} else if (bodyPartContentType.toLowerCase().contains(
						"multipart/alternative")) {

					MimeMultipart mime = (MimeMultipart) dataHandler
							.getContent();
					for (int j = 0; j < mime.getCount(); j++) {
						String ctType = mime.getBodyPart(j).getDataHandler()
								.getContentType();

						if (ctType.toLowerCase().contains("text/plain")) {
							String ctContent = mime.getBodyPart(j)
									.getDataHandler().getContent().toString();
							jtxtContentHTML.setContentType(ctType);
							jtxtContentHTML.setText(ctContent);
						} else if (ctType.toLowerCase().contains("text/html")) {
							Object ct = mime.getBodyPart(j).getDataHandler()
									.getContent();
							addButtonToAttachmentPanel(mime.getBodyPart(j));
						}
					}
					jtxtContentHTML.setContentType(dataHandler.getContentType()
							.toLowerCase());
					jtxtContentHTML.setText(txt);
				} else if (bodyPartContentType.toLowerCase().contains(
						"text/plain")) {
					jtxtContentHTML.setContentType(bodyPartContentType
							.toLowerCase());
					jtxtContentHTML.setText(bodyPartContent.toString());
				} else if (bodyPartContentType.toLowerCase().contains(
						"text/html")) {
					addButtonToAttachmentPanel(bodyPart);
				}
			}
		}
	}

	private void addButtonToAttachmentPanel(final BodyPart bodyPart)
			throws MessagingException, IOException {
		final String contentType = bodyPart.getContentType();
		String btnText = "";
		final Object content = bodyPart.getContent();
		if (contentType.toLowerCase().contains("text/html")) {
			btnText = contentType;
			// content = bodyPart.getContent();
		} else {
			btnText = bodyPart.getFileName();
			// content = contentType;
		}
		JButton btn = new JButton(btnText);
		// btn.addActionListener(new ActionListener() {

		// @Override
		// public void actionPerformed(ActionEvent e) {
		// try {
		// final loadingDlg loadingDialog = new
		// loadingDlg(MainForm.getFrames()[0], bodyPart);//contentType,
		// content);
		// SwingUtilities.invokeLater(new Runnable() {
		//
		// @Override
		// public void run() {
		// loadingDialog.show();
		// }
		// });
		// } catch (IOException ex) {
		// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null,
		// ex);
		// } catch (MessagingException ex) {
		// Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null,
		// ex);
		// showError(ex.getMessage(), false);
		// }
		// }

		pnAttachment.add(btn);
	}

	// <editor-fold defaultstate="collapsed" desc="load mail lÃªn grid inbox">
	/**
	 * load mail lÃªn grid inbox
	 * 
	 * @param flag
	 * @param not
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	private void retriveMessages(Flag flag, boolean not)
			throws MessagingException, UnsupportedEncodingException {
		Message[] messages = mailUtilities.folder.getMessages();
		int j = 0;
		DefaultTableModel tableModel = (DefaultTableModel) jtbInbox.getModel(); // new
																				// DefaultTableModel(new
																				// Object[][]{},
																				// new
																				// String[]{"",
																				// "From",
																				// "Subject",
																				// "Date"});

		tableModel.setRowCount(0);

		for (int i = messages.length - 1; i >= 0; i--) { // (Message message :
															// messages) {
			Message msg = messages[i];
			try {
				Flags flags = msg.getFlags();
				if (flags.contains(flag) == not) {
					MyClientMail myMail = new MyClientMail();
					myMail.getEnvelope(msg);
					Object[] newRow = new Object[] {
							Integer.toString(msg.getMessageNumber()),
							myMail.getFrom(), myMail.getSubject(),
							myMail.getSendDate() };
					tableModel.addRow(newRow);
				}
				j = tableModel.getRowCount();
				jLabel1.setText("Fetching " + j + "/" + messages.length
						+ " message(s)...");
			} catch (MessagingException ex) {
				showError(ex.getMessage() + " Message: " + (i + 1), false);
				i--;
			}
		}
		if (j == 0) {
			jLabel1.setText("");
		} else if (j == messages.length) {
			jLabel1.setText("Fetching " + j + " Message(s) Done!");
		} else {
			jLabel1.setText("Fetching Messages Failed! Total: " + j + "/"
					+ messages.length);

		}
	}

	private void retriveInboxMessages() throws MessagingException,
			UnsupportedEncodingException {
		Message[] messages = mailUtilities.folder.getMessages();
		int j = 0;
		DefaultTableModel tableModel = (DefaultTableModel) jtbInbox.getModel(); // new
																				// DefaultTableModel(new
																				// Object[][]{},
																				// new
																				// String[]{"",
																				// "From",
																				// "Subject",
																				// "Date"});

		tableModel.setRowCount(0);

		for (int i = messages.length - 1; i >= 0; i--) { // (Message message :
															// messages) {
			Message msg = messages[i];
			try {
				Flags flags = msg.getFlags();
				if (!flags.contains(Flags.Flag.DELETED)) {
					MyClientMail myMail = new MyClientMail();
					myMail.getEnvelope(msg);
					Object[] newRow = new Object[] {
							Integer.toString(msg.getMessageNumber()),
							myMail.getFrom(), myMail.getSubject(),
							myMail.getSendDate() };
					tableModel.addRow(newRow);
				}
				j = tableModel.getRowCount();
				jLabel1.setText("Fetching " + j + "/" + messages.length
						+ " message(s)...");
			} catch (MessagingException ex) {
				showError(ex.getMessage() + " Message: " + (i + 1), false);
				i--;
			}
		}
		if (j == 0) {
			jLabel1.setText("");
		} else if (j == messages.length) {
			jLabel1.setText("Fetching " + j + " Message(s) Done!");
		} else {
			jLabel1.setText("Fetching Messages Failed! Total: " + j + "/"
					+ messages.length);

		}
	}

	// </editor-fold>

	private void showError(String message, boolean exit) {
		JOptionPane.showMessageDialog(this, message, "Error",
				JOptionPane.ERROR_MESSAGE);
		if (exit) {
			System.exit(0);
		}
	}

	private void showSuccess(String message, boolean exit) {
		JOptionPane.showMessageDialog(this, message, "Success",
				JOptionPane.INFORMATION_MESSAGE);
		if (exit) {
			System.exit(0);
		}
	}

	private loadingDlg showLoadingDialog() {
		final loadingDlg loading = new loadingDlg(this);
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				loading.show();
			}
		});
		return loading;
	}

	public void open() {
		this.setExtendedState(MAXIMIZED_BOTH);
		this.setVisible(true);
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;

				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(MainForm.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(MainForm.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(MainForm.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(MainForm.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				new MainForm().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JMenuItem aboutMenuItem;
	private javax.swing.JMenu connectMenu;
	private javax.swing.JMenu helpMenu;
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton5;
	private javax.swing.JComboBox jComboBox1;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JList jList1;
	private javax.swing.JMenu jMenu1;
	private javax.swing.JMenu jMenu2;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JPanel jPanel5;
	private javax.swing.JPanel jPanel6;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JScrollPane jScrollPane4;
	private javax.swing.JTabbedPane jTabRight;
	private javax.swing.JTabbedPane jTabbedPane1;
	private javax.swing.JButton jbtnAttachment;
	private javax.swing.JButton jbtnNewMail;
	private javax.swing.JButton jbtnSendMail;
	private javax.swing.JButton jbtnViewMessage;
	private javax.swing.JComboBox jcbxCrypto;
	private javax.swing.JCheckBox jcbxIsSign;
	private javax.swing.JComboBox jcbxProtocol;
	private javax.swing.JPanel jlTabLeft;
	private javax.swing.JLabel jlbDrafts;
	private javax.swing.JLabel jlbFrom;
	private javax.swing.JLabel jlbFrom1;
	private javax.swing.JLabel jlbInbox;
	private javax.swing.JLabel jlbNewMessage;
	private javax.swing.JLabel jlbSent;
	private javax.swing.JLabel jlbSubject;
	private javax.swing.JLabel jlbSubject1;
	private javax.swing.JLabel jlbTo;
	private javax.swing.JLabel jlbTo1;
	private javax.swing.JLabel jlbTrash;
	private javax.swing.JLabel jlbUnread;
	private javax.swing.JLabel jlbUnreadMessage;
	private javax.swing.JLabel jlbsendDate;
	private javax.swing.JPanel jpnInbox;
	private javax.swing.JPanel jpnNewMessage;
	private javax.swing.JPanel jpnSubject;
	private javax.swing.JPanel jpnSubject1;
	private javax.swing.JPanel jpnViewMessage;
	private javax.swing.JTable jtbInbox;
	private javax.swing.JScrollPane jtxt;
	private javax.swing.JEditorPane jtxtComposeMail;
	private javax.swing.JEditorPane jtxtContentHTML;
	private javax.swing.JPasswordField jtxtKey;
	private javax.swing.JEditorPane jtxtMailContent;
	private javax.swing.JTextField jtxtSubject;
	private javax.swing.JTextField jtxtTo;
	private javax.swing.JLabel lbWelcome;
	private javax.swing.JMenuBar menuBar;
	private javax.swing.JPanel pnAttachment;
	private javax.swing.JPanel pnAttachtmentSendMail;
	private javax.swing.JPanel pnHeader;
	private javax.swing.JProgressBar progressBar;
	private javax.swing.JSplitPane slpBodyContent;
	private JButton btnDelete;
}
